package com.example.bookkeepingelf.base.utils;

import com.example.bookkeepingelf.base.enums.WeekEnum;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
    private DateUtils(){}

    public static String DATE_TEMPLATE_1 = "yyyy-MM-dd HH:mm:ss";

    /**
     * 字符串转日期
     * @param dateString
     * @param pattern
     * @return
     */
    public static Date stringToDate(String dateString, String pattern) {
        if (dateString == null || dateString.trim().length() == 0) {
            return null;
        }
        if (pattern == null || pattern.trim().length() == 0) {
            pattern = DATE_TEMPLATE_1;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        try {
            return formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 日期转字符串
     * @param date
     * @param pattern
     * @return
     */
    public static String dateToString(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        if (pattern == null || pattern.trim().length() == 0) {
            pattern = DATE_TEMPLATE_1;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    /**
     * 获取指定日期是星期几
     *
     * @param date
     * @return
     */
    public static int getDayOfWeek(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("date is null");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }


    /**
     * 获取指定日期是星期几
     *
     * @param date
     * @return
     */
    public static String getDayOfWeekStr(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("date is null");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return getDayName(dayOfWeek);
    }

    private static String getDayName(int dayOfWeek) {
        WeekEnum weekEnum = WeekEnum.getWeekEnum(dayOfWeek);
        switch (weekEnum) {
            case SUNDAY:
                return "星期日";
            case MONDAY:
                return "星期一";
            case TUESDAY:
                return "星期二";
            case WEDNESDAY:
                return "星期三";
            case THURSDAY:
                return "星期四";
            case FRIDAY:
                return "星期五";
            case SATURDAY:
                return "星期六";
            default:
                return "未知";
        }
    }

}
